from email.policy import default
from rest_framework import serializers
from .models import Question,Choice,User

class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = ['id','question_text','pub_date']

class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = ['id','question_id','choice_text','votes']
    

class QuestionDetailSerializer(serializers.ModelSerializer):
    choices = ChoiceSerializer(
        many=True,
        read_only=True
    )

    class Meta:
        model = Question
        fields = ['id','question_text','pub_date','choices']

class UserProfileSerializer(serializers.ModelSerializer):

    def validate_nickname(self,value):
        '''
        禁止空名
        '''
        if value == '':
            raise serializers.ValidationError("禁止空名")
        return value

    def validate_age(self,value):
        '''
        禁止超级长寿
        '''
        if value >= 150:
            raise serializers.ValidationError("禁止超级长寿")
        return value

    class Meta:
        model = User
        fields = ['id','gender','age','motto','nickname']
        read_only_fields = ('id',)


class UserProfileListSerializer(serializers.ModelSerializer):
    '''
    列出数据库中用户
    '''
    class Meta:
        model = User
        fields = ['id','gender','age','nickname']
        read_only_fields = ('id','gender','age','nickname',)